package com.appdemo.demo.controller;


import com.appdemo.demo.fact.Request;
import com.appdemo.demo.fact.User;
import com.appdemo.demo.init.ConfigRules;
import com.appdemo.demo.result.CalculateResult;
import com.appdemo.demo.rule.MyRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class UserController {

    @Autowired
    @Qualifier("myEngine")
    RulesEngine myEngine;

    @Autowired
    ConfigRules configRules;

    @RequestMapping(value = "/jsonRule", method = RequestMethod.POST)
    public Object jsonRule(@RequestBody User user) throws Exception {
        // 拉取规则
        Rules rules = configRules.fetchConfigRules();
        Facts facts = new Facts();
        user.setUniqueId(UUID.randomUUID().toString());

        // 执行规则
        myEngine.fire(rules, facts);

        return null;
    }


    @RequestMapping(value = "/myRule", method = RequestMethod.POST)
    public Object myRule(@RequestBody Request request) throws Exception {
        MyRule<Request, CalculateResult> rule = new MyRule<>();
        Rules rules = new Rules(rule);
        Facts facts = new Facts();
        request.getUser().setUniqueId(UUID.randomUUID().toString());
        facts.put("request", request);
        myEngine.fire(rules, facts);
        if (rule.isExecuted()) {
            CalculateResult userResult = rule.getResult();
            System.out.println("result from final ruls" + userResult.toString());
            return userResult;
        } else {
            return null;
        }
    }
}

